<template>
    <div class="shopping-cart-container">
        <h2 class="cart-title">我的购物车</h2>

        <!-- 购物车列表 -->
        <div class="cart-list">
            <el-table :data="cartItems" style="width: 100%" border>
                <el-table-column width="50">
                    <template #header>
                        <el-checkbox v-model="selectAll" @change="handleSelectAll"></el-checkbox>
                    </template>
                    <template #default="scope">
                        <el-checkbox v-model="scope.row.selected"
                            @change="() => handleItemSelected(scope.row)"></el-checkbox>
                    </template>
                </el-table-column>
                <el-table-column label="商品信息">
                    <template #default="scope">
                        <div class="item-info">
                            <img :src="scope.row.imageUrl" :alt="scope.row.name" class="item-image" />
                            <span class="item-name">{{ scope.row.name }}</span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="单价" width="120" align="center">
                    <template #default="scope">
                        ¥{{ scope.row.price.toFixed(2) }}
                    </template>
                </el-table-column>
                <el-table-column label="数量" width="150" align="center">
                    <template #default="scope">
                        <el-input-number v-model="scope.row.quantity" :min="1"
                            @change="() => handleQuantityChange(scope.row)"></el-input-number>
                    </template>
                </el-table-column>
                <el-table-column label="小计" width="120" align="center">
                    <template #default="scope">
                        <span class="item-subtotal">¥{{ (scope.row.price * scope.row.quantity).toFixed(2) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="100" align="center">
                    <template #default="scope">
                        <el-button type="danger" size="small" @click="handleDelete(scope.row.productId)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 当购物车中没有商品时显示提示信息 -->
            <div v-if="cartItems.length === 0" class="empty-cart-tip">
                <p>您的购物车目前为空</p>
            </div>
        </div>

        <!-- 结算区域 -->
        <div class="checkout-section">
            <div class="coupon-selector">
                <span>优惠券：</span>
                <el-select v-model="selectedCoupon" placeholder="请选择优惠券" class="coupon-select"
                    @focus="handleCouponSelectOpen">
                    <el-option v-for="(coupon, index) in couponOptions" :key="index"
                        :label="`优惠${coupon.discountAmount / 100}元`" :value="JSON.stringify(coupon.ids)">
                        叠加{{ coupon.ids.length }}券：【优惠{{ coupon.discountAmount / 100 }}元】
                    </el-option>
                    <el-option label="无优惠" value="">无优惠</el-option>
                </el-select>
            </div>

            <div class="summary">
                <div class="summary-info">
                    <span>已选 {{ selectedItemsCount }} 件商品</span>
                    <span v-if="selectedCouponNames.length > 0" class="selected-coupons">
                        使用优惠券: {{ selectedCouponNames.join(', ') }}
                    </span>
                </div>
                <span class="total-price">总计：¥{{ totalPrice.toFixed(2) }}</span>
                <el-button type="danger" @click="handleCheckout">去结算</el-button>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import cartApi from '@/api/cart'
import orderApi from '@/api/order'
import { useProfileStore } from '@/store/profile'
import { CartItemResponse as CartItemType } from '@/type/cart'
import promotionApi from '@/api/promotion'
import { OrderProductDTO, CouponDiscountDTO } from '@/type/coupon'
import { CouponDetailVO } from '@/type/coupon'

const router = useRouter()


const cartItems = ref<CartItemType[]>([])
const selectAll = ref(true)
const selectedCoupon = ref('')
const couponDetails = ref<{ [key: string]: CouponDetailVO }>({})


// 获取购物车列表
const fetchCartList = async () => {
    try {
        const res = await cartApi.getCartList()
        cartItems.value = res.data.data
    } catch (error) {
        console.error('获取购物车失败:', error)
        ElMessage.error('获取购物车失败')
    }
}

// 数量变化
const handleQuantityChange = async (item: CartItemType) => {
    try {
        await cartApi.updateCart({
            productId: item.productId,
            quantity: item.quantity,
            selected: item.selected
        })
        fetchBestDealCoupons() // 添加这行来更新优惠券选项
    } catch (error) {
        console.error('更新购物车失败:', error)
        ElMessage.error('更新购物车失败')
    }
}

// 删除商品
const handleDelete = async (productId: number) => {
    try {
        await ElMessageBox.confirm('确定要删除该商品吗?', '提示', {
            type: 'warning',
            confirmButtonText: '确定',
            cancelButtonText: '取消'
        })
        await cartApi.deleteCart(productId)
        ElMessage.success('删除成功')
        fetchCartList()
    } catch (error) {
        console.error('删除失败:', error)
    }
}

// 全选
const handleSelectAll = async (val: boolean) => {
    cartItems.value.forEach(item => {
        item.selected = val
    })

    // 批量更新所有商品的选中状态
    try {
        const updatePromises = cartItems.value.map(item =>
            cartApi.updateCart({
                productId: item.productId,
                quantity: item.quantity,
                selected: item.selected
            })
        )
        await Promise.all(updatePromises)
        fetchBestDealCoupons() // 添加这行来更新优惠券选项
    } catch (error) {
        console.error('更新购物车失败:', error)
        ElMessage.error('更新购物车失败')
    }
}

// 单个商品选择
const handleItemSelect = () => {
    selectAll.value = cartItems.value.every(item => item.selected)
}

// 商品选择变化
const handleItemSelected = async (item: CartItemType) => {
    try {
        await cartApi.updateCart({
            productId: item.productId,
            quantity: item.quantity,
            selected: item.selected
        })
        handleItemSelect()
        fetchBestDealCoupons() // 添加这行来更新优惠券选项
    } catch (error) {
        console.error('更新购物车失败:', error)
        ElMessage.error('更新购物车失败')
    }
}

// 去结算
const handleCheckout = async () => {
    const selectedItems = cartItems.value.filter(item => item.selected)
    if (selectedItems.length === 0) {
        ElMessage.warning('请选择要结算的商品')
        return
    }

    try {
        // 获取选中的优惠券ID列表
        let couponIds: string[] = []
        if (selectedCoupon.value) {
            try {
                couponIds = JSON.parse(selectedCoupon.value)
            } catch (e) {
                console.error('解析优惠券信息失败:', e)
                couponIds = []
            }
        }
        
        // 创建订单，传递优惠券ID列表
        const res = await orderApi.createOrder(selectedItems, couponIds)
        const orderSnapshot = res.data.data
        
        // 跳转到订单页面，传递订单编号
        router.push({
            path: 'order',
            query: {
                orderNo: orderSnapshot.orderNo
            }
        })
    } catch (error) {
        console.error('创建订单失败:', error)
        ElMessage.error('创建订单失败')
    }
}

// 计算属性
const selectedCouponIds = computed(() => {
    if (!selectedCoupon.value) return []
    try {
        return JSON.parse(selectedCoupon.value)
    } catch (e) {
        return []
    }
})

// 获取选中的优惠券名称
const selectedCouponNames = computed(() => {
    if (selectedCouponIds.value.length === 0) return []

    return selectedCouponIds.value.map((id: any) => {
        const coupon = couponDetails.value[id]
        return coupon ? coupon.name : `优惠券(${id})`
    })
})

// 获取选中商品数量
const selectedItemsCount = computed(() => {
    return cartItems.value.filter(item => item.selected).length
})

const totalPrice = computed(() => {
    let total = cartItems.value
        .filter(item => item.selected)
        .reduce((sum, item) => sum + (item.price * item.quantity), 0)

    // 修复优惠券匹配逻辑
    if (selectedCouponIds.value.length > 0) {
        const selectedCouponOption = couponOptions.value.find(coupon =>
            coupon.ids.length === selectedCouponIds.value.length &&
            coupon.ids.every(id => selectedCouponIds.value.includes(id))
        )

        if (selectedCouponOption) {
            total -= selectedCouponOption.discountAmount / 100 // 金额单位转换（分转元）
        }
    }

    return Math.max(0, total); // 确保价格不低于0
})

// 获取选中的购物车项
const getSelectedProducts = (): OrderProductDTO[] => {
    return cartItems.value
        .filter(item => item.selected)
        .map(item => ({
            productId: item.productId,
            quantity: item.quantity,
            price: item.price
        }))
}

const couponOptions = ref<CouponDiscountDTO[]>([])

// 获取优惠券
const fetchBestDealCoupons = async () => {
    const products = getSelectedProducts()
    if (products.length === 0) {
        couponOptions.value = []
        return
    }

    try {
        const coupons = await promotionApi.getBestDealCoupon(products)
        couponOptions.value = coupons.data.data
        // 获取新优惠券的详细信息
        const allCouponIds = coupons.data.data.flatMap((coupon: CouponDiscountDTO) => coupon.ids)
        await fetchCouponDetails(allCouponIds)
        console.log(coupons.data)
    } catch (error) {
        console.error('获取最佳优惠券失败:', error)
        ElMessage.error('获取最佳优惠券失败')
    }
}

// 根据优惠券ID获取优惠券详情
const fetchCouponDetails = async (couponIds: string[]) => {
    const needFetchIds = couponIds.filter(id => !couponDetails.value[id])

    if (needFetchIds.length === 0) return

    try {
        const fetchPromises = needFetchIds.map(id =>
            promotionApi.getCouponById(id)
        )

        const results = await Promise.all(fetchPromises)

        results.forEach((result, index) => {
            const id = needFetchIds[index]
            couponDetails.value[id] = result.data.data
        })
    } catch (error) {
        console.error('获取优惠券详情失败:', error)
        ElMessage.error('获取优惠券详情失败')
    }
}

// 监听选中的优惠券变化，获取详细信息
watch(selectedCouponIds, async (newIds) => {
    if (newIds.length > 0) {
        await fetchCouponDetails(newIds)
    }
})

onMounted(() => {
    fetchCartList()
})

const handleCouponSelectOpen = () => {
    fetchBestDealCoupons() // 用户点击下拉框时获取最佳优惠券
}

onMounted(() => {
    fetchCartList()
})
</script>

<style scoped>
.shopping-cart-container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
}

.cart-title {
    font-size: 24px;
    margin-bottom: 20px;
    color: #333;
}

.cart-list {
    background: #fff;
    border-radius: 4px;
    padding: 20px;
    margin-bottom: 20px;
}

.item-info {
    display: flex;
    align-items: center;
}

.item-image {
    width: 80px;
    height: 80px;
    margin-right: 15px;
    object-fit: cover;
}

.item-name {
    flex: 1;
}

.item-subtotal {
    color: #f56c6c;
    font-weight: bold;
}

.checkout-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    background: #fff;
    border-radius: 4px;
}

.coupon-selector {
    display: flex;
    align-items: center;
}

.coupon-select {
    width: 200px;
}

.summary {
    display: flex;
    align-items: center;
    gap: 20px;
}

.summary-info {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
}

.selected-coupons {
    font-size: 14px;
    color: #67c23a;
    margin-top: 5px;
}

.total-price {
    font-size: 18px;
    color: #f56c6c;
    font-weight: bold;
}

.empty-cart-tip {
    text-align: center;
    padding: 50px;
    font-size: 16px;
    color: #999;
}

.empty-cart-tip p {
    margin: 0;
}
</style>